<template>
  <a-modal
    title="编辑任务"
    :visible.sync="visible"
    @ok="handleSubmit"
    @cancel="handleCancel(false)"
  >
    <a-form :form="form">
      <a-form-item
        label="标题"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          disabled
          v-decorator="[
            'title',
            {
              initialValue: initInfo.title,
              rules: [{ required: true, message: '请输入标题！' }]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="描述"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-textarea
          :rows="3"
          v-decorator="['describe', { initialValue: initInfo.describe }]"
        />
      </a-form-item>
      <a-form-item
        label="缩略图"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        help="限上传一张缩略图，图片最佳尺寸为64px*64px"
      >
        <div class="clearfix">
          <a-upload
            v-decorator="[
              'img',
              {
                initialValue: initInfo.img,
                valuePropName: 'fileList',
                getValueFromEvent: normFile,
                rules: [{ required: true, message: '请上传缩列图' }]
              }
            ]"
            accept="image/*"
            listType="picture-card"
            name="file"
            :multiple="false"
            :showUploadList="false"
            :action="$api.upload"
            :data="postData"
            :beforeUpload="beforeUpload"
          >
            <img
              v-if="imageUrl"
              :src="$api.picPre + imageUrl"
              alt="avatar"
              style="width: 64px"
            />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传缩略图</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>
      <a-form-item
        label="积分"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input-number
          :min="1"
          v-decorator="[
            'integral',
            {
              initialValue: initInfo.integral,
              rules: [{ required: true, message: '请输入积分！' }]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="排序"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input-number
          :min="1"
          v-decorator="[
            'sort',
            {
              initialValue: initInfo.sort,
              rules: [{ required: true, message: '请输入排序！' }]
            }
          ]"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { getToken } from "@/tool/qiniu";
export default {
  name: "add",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editInfo: {
      type: Object
    }
  },
  data() {
    this.handleSubmit = this.$debounce(this.handleSubmit, 800);
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this),
      initInfo: {},
      postData: {
        token: ""
      },
      imageUrl: "",
      loading: false
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          if (values.img) {
            values.img = values.img[0].response.key;
          }
          let obj = JSON.parse(JSON.stringify(values));
          obj.id = this.initInfo.id;
          this.$ajax
            .post(this.$api.editActivityList, obj)
            .then(() => {
              this.$notification.success({
                message: "操作成功"
              });
              this.handleCancel(true);
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        }
      });
    },
    handleCancel(isFresh) {
      this.form.resetFields();
      this.$emit("handleCancel", isFresh);
    },
    normFile(e) {
      if (e.file.status === "uploading") {
        this.loading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageUrl = e.file.response.key;
        this.loading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "taskIcon/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 64;
        let height = 64;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为64px*64px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    }
  },
  watch: {
    editInfo: {
      handler: function(val) {
        this.initInfo = JSON.parse(JSON.stringify(val));
        this.imageUrl = this.initInfo.img;
        this.initInfo.img = [
          {
            uid: "1",
            status: "done",
            url: this.$api.picPre + this.initInfo.img,
            name: this.initInfo.title,
            response: {
              key: this.initInfo.img
            }
          }
        ];
      },
      deep: true
    }
  }
};
</script>

<style scoped></style>
